import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/bloc/auth/auth_event.dart';

import '../../bloc/auth/auth_bloc.dart';
import '../../bloc/auth/auth_state.dart';
import '../../bloc/home/home_bloc.dart';
import '../../bloc/home/home_event.dart';
import '../../dialog/EnterpriseBindingDialog.dart';
import '../../dialog/dialog1.dart';
import '../../generated/assets.dart';
import '../../models/user_company.dart';
import '../../widgets/financial_card.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('章鱼问账'),
        backgroundColor: const Color(0xFFE3F2FD),
        elevation: 0,
        centerTitle: true,
      ),
      body: SafeArea(
        child: Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFFE3F2FD), Color(0xCCE3F2FD)],
              stops: [0.0, 0.4],
            ),
          ),
          // decoration: const BoxDecoration(
          //   gradient: LinearGradient(
          //     begin: Alignment.topCenter,
          //     end: Alignment.bottomCenter,
          //     colors: [Color(0xFFE3F2FD), Colors.white],
          //     stops: [0.0, 0.3],
          //   ),
          // ),
          child: ListView(
            padding: const EdgeInsets.all(16.0),
            children: [
              _buildCompanyInfoCard(context),
              const SizedBox(height: 20),
              _buildActionListCard(context),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCompanyInfoCard(BuildContext context) {
    return FinancialCard(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              BlocSelector<AuthBloc, AuthState, AppCompanyDto?>(
                selector: (state) {
                  if (state is AuthAuthenticated) {
                    return state.user?.appCompanyDto;
                  }
                  return null;
                },
                builder: (context, company) {
                  return Row(
                    children: [
                      Text('企业名称: ', style: const TextStyle(fontSize: 16)),
                      const SizedBox(width: 8),
                      company?.name != null
                          ? Text('${company?.name}', style: const TextStyle(fontSize: 16))
                          : GestureDetector(
                            onTap: ()  async {
                              final result = await EnterpriseBindingDialog.show(context);
                              if (result != null) {
                                context.read<HomeBloc>().add(
                                  AddCompany(LinkedHashMap<String, dynamic>.from(result)),
                                );
                                // 处理返回的数据
                                print('企业信息: $result');
                              }
                            },
                          child: Text('【未绑定企业】', style: const TextStyle(fontSize: 16, color: Color(0xff3FC7DD)))),
                    ],
                  );
                },
              ),
              const SizedBox(height: 8),
              BlocSelector<AuthBloc, AuthState, AppCompanyDto?>(
                selector: (state) {
                  if (state is AuthAuthenticated) {
                    return state.user?.appCompanyDto;
                  }
                  return null;
                },
                builder: (context, company) {
                  return Row(
                    children: [
                      Text('税务验证: ', style: const TextStyle(fontSize: 16)),
                      const SizedBox(width: 8),
                      // company?.loginWay != null
                      //     ? Text('${company?.loginWay}', style: const TextStyle(fontSize: 16)):
                          GestureDetector(
                          onTap: () async {
                            // context.push('/company-bind');
                            context.push('/company_verification');
                          },
                          child: Text('【进行验证】', style: const TextStyle(fontSize: 16, color:  Color(0xff3FC7DD)))),
                    ],
                  );
                },
              ),
            ],
          ),
        ],
      ),
    );
  }





  Widget _buildActionListCard(BuildContext context) {
    return FinancialCard(
      child: Column(
        children: [
          _buildActionItem(
            context,
            Image.asset( Assets.iconIconQyxxqh, width: 17, height: 17),
            '企业信息切换', () {
              context.push('/company-list');
              // context.push('/company-listen');
            },
          ),
          const Divider(),
          _buildActionItem(context,  Image.asset( Assets.iconIconWdfwdd, width: 17, height: 17), '我的服务订单', () {
            context.push('/service-list');
          }),
          // const Divider(),
          // _buildActionItem(context, Icons.support_agent, '联系税务专家', null),
          // const Divider(),
          // _buildActionItem(context, Icons.lock_outline, '修改我的密码', null),
          const Divider(),
          _buildActionItem(context,  Image.asset( Assets.iconIconTczzdl, width: 17, height: 17), '退出账号登录', () {
            showLogoutDialog(context, onConfirm: () {
                context.read<AuthBloc>().add(AuthLogoutPress());
            }, onCancel: () {
              Navigator.of(context).pop();
            });
          }),
        ],
      ),
    );
  }

  Widget _buildActionItem(
    BuildContext context, Widget icon,
    String title,
      GestureTapCallback? onTapCallback,
  ) {
    return InkWell(
      onTap:onTapCallback,
      child: SizedBox(
          height: 50,
          width: double.infinity,
        child: Row(
          children: [
            icon,
            const SizedBox(width: 6),
            Text(title, style: const TextStyle(fontSize: 16)),
            Expanded(child: Container()),
            Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colors.grey.shade400,
            )
          ]
        ),
      ),
    );


    return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 0.0),
      leading: icon,
      minLeadingWidth: 0,
      title: Text(title),
      trailing: Icon(
        Icons.arrow_forward_ios,
        size: 16,
        color: Colors.grey.shade400,
      ),
      onTap: () {

      },
    );
  }
}
